#!/bin/bash

# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

. /usr/share/clearwater/utils/check-root-permissions 2

local_site_name=site1
. /etc/clearwater/config

FILEPATH=$1
KEY=$2
SCHEMA=$3
ALLOW_LARGE_UPLOADS=$4



function usage() {
  echo "Usage: upload_generic_json <filepath> <key> [<schema>] [--allow-large]"
}

if [[ $1 == "" || $2 == "" ]]
then
  usage
  exit 2
fi

# Check that the file is already present. The config file should either be put
# in place by the user, or created by the plugin at startup if it finds both
# the file and etcd key missing. If it does not exist, the disk may have been
# full, or some other error may have occured.
if [[ ! -f $FILEPATH ]]
then
  echo "No configuration file found at $FILEPATH"
  exit 2
elif [[ ! -s $FILEPATH ]]
then
  echo "The configuration file at $FILEPATH is empty, uploading a blank file"
elif [[ -f $SCHEMA ]]
then
  # Validate config json against schema for syntactic errors
  python /usr/share/clearwater/clearwater-config-manager/scripts/validate_json.py $SCHEMA $FILEPATH

  # Abort uploading and warn user if validation fails
  rc=$?
  if [[ $rc != 0 ]]; then
    echo "Unable to upload $FILEPATH as it is invalid. Please fix up the errors and retry"
    exit $rc
  fi
fi

# Check we can contact `etcd`
if ! nc -z ${management_local_ip:-$local_ip} 4000
then
  echo "The Clearwater Configuration store (etcd) is not running"
  echo "Please start it before uploading configuration"
  exit 2
fi

# Reject file that is too large for etcd. But allow larger file if the script is
# called with --allow-large, so that the wrapper script is backward compatible.
# All scripts calling this function will pass the optional argument directly to
# this function to check if it's --allow-large
uploadsize=10000
filesize=$(wc -c <"$FILEPATH")
if [[ $filesize -ge $uploadsize && $ALLOW_LARGE_UPLOADS != "--allow-large" ]]
then
  echo "The configuration file at $FILEPATH is larger than the recommended size of $uploadsize bytes"
  echo "Please re-run the command with the --allow-large flag if you want to force upload the file"
  exit 2
fi

# Upload the file to etcd
keypath=http://${management_local_ip:-$local_ip}:4000/v2/keys/clearwater/$local_site_name/configuration/$KEY
curl -X PUT $keypath --data-urlencode value@$FILEPATH 2> /tmp/upload-json-file.stderr.$$ | tee /tmp/upload-json-file.stdout.$$ | egrep -q "\"action\":\"set\""
rc=$?

# Check the return code and log if appropriate.
if [ $rc != 0 ] ; then
  echo Failed to upload the configuration file to $keypath  >&2
  cat /tmp/upload-json-file.stderr.$$                       >&2
  cat /tmp/upload-json-file.stdout.$$                       >&2
fi
rm -f /tmp/upload-json-file.stderr.$$ /tmp/upload-json-file.stdout.$$

exit $rc
